<template>
  <el-card>

    <!--  表格操作  -->
    <div class="select-div">
      <el-form :inline="true" style="height: 40px">

        <el-form-item>
          <el-input
              clearable
              v-model="condition.uri"
              prefix-icon="el-icon-search"
              size="small"
              placeholder="请输入接口关键字"
              style="width:200px"
              @keyup.enter.native="searchLogs"
          />
        </el-form-item>

        <el-form-item>
          <el-input
              clearable
              v-model="condition.username"
              prefix-icon="el-icon-search"
              size="small"
              placeholder="请输入操作用户关键字"
              style="width:200px"
              @keyup.enter.native="searchLogs"
          />
        </el-form-item>

        <el-form-item>
          <my-select v-model="condition.method"
                     placeholder="请选择请求方式"
                     :showList="condition.methodList"
                     labelName='label'
                     valueName='value'/>
        </el-form-item>

        <el-form-item>
          <el-input
              clearable
              v-model="condition.ip"
              prefix-icon="el-icon-search"
              size="small"
              placeholder="请输入ip关键字"
              style="width:200px"
              @keyup.enter.native="searchLogs"
          />
        </el-form-item>

        <el-button type="primary" size="small" icon="el-icon-search" style="margin-left:1rem"
                   @click="searchLogs">
          搜索
        </el-button>

        <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteCheck()"
                   :disabled="this.selection.length === 0">删除选中
        </el-button>

        <el-button type="primary" size="small" @click="downloadExcel">导出Excel</el-button>

      </el-form>
    </div>

    <!--  表格内容  -->
    <el-table :data="tableData"
              border
              :header-cell-style="{'text-align':'center'}"
              :cell-style="{'text-align':'center'}"
              @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column prop="uri" label="操作接口"></el-table-column>

      <el-table-column prop="username" label="操作用户"></el-table-column>

      <el-table-column prop="method" label="请求方式">
        <template slot-scope="scope" v-if="scope.row.method">
          <el-tag :type="tagType(scope.row.method)">
            {{ scope.row.method }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="ip" label="ip地址"></el-table-column>

      <el-table-column prop="region" label="所属地区"></el-table-column>

      <el-table-column prop="param" label="请求参数" show-overflow-tooltip></el-table-column>

      <el-table-column prop="elapsedTime" label="接口耗时(ms)"></el-table-column>

      <el-table-column prop="createTime" label="操作时间"></el-table-column>

      <el-table-column label="操作" fixed="right">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="查看详情" placement="top-start">
            <el-button circle icon="el-icon-document" size="mini"
                       @click="showInfo(scope.row.id)"/>
          </el-tooltip>

          <el-tooltip effect="dark" content="删除" placement="top-start">
            <el-button circle icon="el-icon-delete" size="mini" placement="top-start" type="danger"
                       @click="deleteCheck(scope.row.id)"/>
          </el-tooltip>
        </template>
      </el-table-column>

    </el-table>

    <!--  分页  -->
    <pagination
        :total="total"
        :page_index="pageNum"
        @pageChange="pageChange"
    />

    <!--  详情弹出框  -->
    <el-dialog
        title="操作详情"
        :visible.sync="dialogInfo"
        width="40%"
        :before-close="handleCloseDialog">
      <el-form :model="logFrom" ref="logFrom" label-width="100px">

        <el-form-item label="操作接口" prop="uri">
          <el-input v-model="logFrom.uri"></el-input>
        </el-form-item>

        <el-form-item label="操作用户" prop="username">
          <el-input v-model="logFrom.username"></el-input>
        </el-form-item>

        <el-form-item label="请求方式" prop="method">
          <el-tag :type="tagType(logFrom.method)">
            {{ logFrom.method }}
          </el-tag>
        </el-form-item>


        <el-form-item label="ip地址" prop="ip">
          <el-input v-model="logFrom.ip"></el-input>
        </el-form-item>

        <el-form-item label="请求参数" prop="param">
          <el-input v-model="logFrom.param"></el-input>
        </el-form-item>

        <el-form-item label="请求数据" prop="payload">
          <el-input type="textarea" v-model="logFrom.payload" :autosize="{ minRows: 2, maxRows: 6 }" class="textarea"/>
        </el-form-item>

      </el-form>
    </el-dialog>

  </el-card>
</template>

<script>
import { logApi } from '@/api';

export default {
  name: "Log",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      selection: [],
      selectedNum: 0,
      condition: {
        uri: null,
        username: null,
        method: null,
        ip: null,
        methodList: [
          {
            value: "GET",
            label: "GET"
          },
          {
            value: "POST",
            label: "POST"
          },
          {
            value: "PUT",
            label: "PUT"
          },
          {
            value: "DELETE",
            label: "DELETE"
          }
        ],
      },
      logFrom: {},
      dialogInfo: false
    }
  },

  methods: {
    /**
     * 分页回调函数
     * @param val
     */
    pageChange(val) {
      this.pageNum = val.pageNum;
      this.pageSize = val.pageSize;
      this.loadLogList();
    },

    /**
     * 复选框事件
     * @param selection 选中数据数组
     */
    handleSelectionChange(selection) {
      this.selection = selection.map(item => item.id)
      this.selectedNum = selection.length
    },

    /**
     * input搜索触发事件
     */
    searchLogs() {
      this.pageNum = 1;
      this.loadLogList();
    },

    /**
     * 当用户通过点击关闭图标或遮罩关闭 Dialog 时起效的事件
     */
    handleCloseDialog() {
      //关闭Dialog时清空表单
      if (this.$refs.logFrom !== undefined) this.$refs.logFrom.resetFields();
      this.logFrom = {};
      this.dialogInfo = false;
    },

    /**
     * 查询详情
     * @param id 数据id
     */
    showInfo(id) {
      this.logFrom = this.tableData.find(obj => obj.id === id)
      this.dialogInfo = true;
    },

    /**
     * 删除数据
     * @param id 数据id
     */
    deleteCheck(id) {
      this.$confirm("确认删除选中记录吗？", "提示", {
        type: "warning"
      }).then(() => {
        const ids = id == null ? this.selection : [id];
        logApi.deleteLogs(ids).then((response) => {
          if (response.data.code === 20000) {
            this.$message({
              message: '删除成功！',
              type: 'success'
            });
            this.loadLogList();
          }
        });
      }).catch(() => {
        // 取消删除操作
      });
    },

    // Excel文件下载
    downloadExcel() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        uri: this.condition.uri,
        username: this.condition.username,
        requestMethod: this.condition.method,
        ip: this.condition.ip,
      };
      
      logApi.exportLogExcel(params).then((response) => {
        const blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});
        const downloadElement = document.createElement('a');
        downloadElement.href = window.URL.createObjectURL(blob);
        downloadElement.download = 'logs.xlsx'; // 更改为更具描述性的文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); // 点击下载链接
        document.body.removeChild(downloadElement); // 下载完成后移除下载链接
      });
    },

    /**
     * 获取日志数据
     */
    loadLogList() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        uri: this.condition.uri,
        username: this.condition.username,
        requestMethod: this.condition.method,
        ip: this.condition.ip,
      };
      
      logApi.getLogList(params).then(response => {
        if (response.data.code === 20000) {
          this.tableData = response.data.data.pagingList;
          this.total = response.data.data.count;
        }
      });
    }
  },

  computed: {
    tagType() {
      return function (type) {
        switch (type) {
          case "GET":
            return "";
          case "POST":
            return "success";
          case "PUT":
            return "warning";
          case "DELETE":
            return "danger";
        }
      };
    }
  },

  created() {
    this.loadLogList();
  }
}
</script>

<style>
.auto-resize .el-textarea__inner {
  resize: vertical; /* 垂直方向自动调整 */
}

.el-table-column--ellipsis {
  max-width: 200px; /* 设置最大宽度 */
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 显示省略号 */
}
</style>